package com.yrxy.thread.interview.base;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author huanglaoxie(微信:yfct-8888)
 * @className ReadWriteLockDemo
 * @description：
 * @date 20176/9 18:58
 */
public class ReadWriteLockDemo {
    private int value = 200;
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    public void read(){
        //使用读锁
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+" : "+ value);
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }

    public void write(int number){
        readWriteLock.writeLock().lock();
        try {
            this.value = number;
            System.out.println(Thread.currentThread().getName()+" : "+number);
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public static void main(String[] args) {
        ReadWriteLockDemo lock = new ReadWriteLockDemo();
        //启动100个读线程
        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    lock.read();
                }
            }," read thread: "+i).start();
        }
        //写线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                lock.write((int)(Math.random()*101));
            }
        },"Write").start();

    }

}
